package com.ktg.mes.wm.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ktg.common.core.domain.APIResult;
import com.ktg.common.utils.SecurityUtils;
import com.ktg.mes.util.LGLeftJoinQueryWrapper;
import com.ktg.mes.wm.domain.*;
import com.ktg.mes.wm.service.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.core.domain.Result;
import com.ktg.common.utils.poi.ExcelUtil;

/**
 * 物料拆分记录Controller
 *
 * @author byteco
 * @date 2023-01-06
 */
@RestController
@RequestMapping("/wm/wmItemSplitLine")
public class WmItemSplitLineController extends BaseController
{
    @Autowired
    private IWmItemSplitLineService wmItemSplitLineService;

    @Autowired
    private IWmItemSplitService wmItemSplitService;

    @Autowired
    private IWmStockOutService wmStockOutService;

    @Autowired
    private IWmAssembleRecptLineService wmAssembleRecptLineService;

    @Autowired
    private IWmItemRecptLineService wmItemRecptLineService;

    @Autowired
    private IWmWarehouseService wmWarehouseService;


    /**
     * 查询物料拆分记录列表
     */
    @PreAuthorize("@ss.hasPermi('wm:wmItemSplitLine:list')")
    @GetMapping("/list")
    public Result<IPage<JSONObject>> list(WmItemSplitLine wmItemSplitLine,
                                          @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                          @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                          HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询物料拆分记录列表",req,null);
        try {
            LGLeftJoinQueryWrapper leftJoinQueryWrapper = new LGLeftJoinQueryWrapper<>(wmItemSplitLine,req.getParameterMap(),pageNo,pageSize);
            IPage pageList = wmStockOutService.lgPageMapList(leftJoinQueryWrapper);
            return apiLog.ok(pageList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 导出物料拆分记录列表
     */
    @PreAuthorize("@ss.hasPermi('wm:wmItemSplitLine:export')")
    @Log(title = "物料拆分记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WmItemSplitLine wmItemSplitLine,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("导出物料拆分记录列表",req,wmItemSplitLine);
        try {
            List<WmItemSplitLine> list = wmItemSplitLineService.queryList(wmItemSplitLine);
            ExcelUtil<WmItemSplitLine> util = new ExcelUtil<WmItemSplitLine>(WmItemSplitLine.class);
            util.exportExcel(response, list, "物料拆分记录数据");
            apiLog.ok(null);
        }catch (Exception e){
            apiLog.error(e);
        }
    }

    /**
     * 获取物料拆分记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('wm:wmItemSplitLine:query')")
    @GetMapping(value = "/{recordId}")
    public Result<WmItemSplitLine> getInfo(@PathVariable("recordId") Long recordId,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("获取物料拆分记录详细信息",req,null);
        try {
            return apiLog.ok(wmItemSplitLineService.getInfo(recordId));
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 新增物料拆分记录
     */
    @PreAuthorize("@ss.hasPermi('wm:wmItemSplitLine:add')")
    @Log(title = "物料拆分记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public Result<String> add(@RequestBody WmItemSplitLine wmItemSplitLine,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("新增物料拆分记录",req,wmItemSplitLine);
        try {
            wmItemSplitLineService.insert(wmItemSplitLine);
            return apiLog.ok("添加成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 修改物料拆分记录
     */
    @PreAuthorize("@ss.hasPermi('wm:wmItemSplitLine:edit')")
    @Log(title = "物料拆分记录", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public Result<String> edit(@RequestBody WmItemSplitLine wmItemSplitLine,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("修改物料拆分记录",req,wmItemSplitLine);
        try {
            wmItemSplitLineService.update(wmItemSplitLine);
            return apiLog.ok("编辑成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 新增物料拆分入库执行
     */
    @PreAuthorize("@ss.hasPermi('wm:wmItemSplitLine:splitInStock')")
    @Log(title = "新增物料拆分入库执行", businessType = BusinessType.INSERT)
    @PostMapping("/splitInStock")
    public Result<String> splitInStock(@RequestBody WmItemSplitLine wmItemSplitLine, HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("新增物料组装入库",req,wmItemSplitLine);
        try {

            WmItemSplit itemSplit = wmItemSplitService.getById(wmItemSplitLine.getItemSplitLineId());
            itemSplit.setIsInStock("1");
            wmItemSplitService.updateById(itemSplit);

            WmWarehouse warehouse = wmWarehouseService.selectWmWarehouseByWarehouseId(itemSplit.getWarehouseId());

            QueryWrapper<WmItemSplitLine> wmItemSplitLineQueryWrapper = new QueryWrapper<WmItemSplitLine>(wmItemSplitLine);
            List<WmItemSplitLine> wmAssembleRecptLineList = wmItemSplitLineService.list(wmItemSplitLineQueryWrapper);


            if (wmAssembleRecptLineList != null && wmAssembleRecptLineList.size() > 0){
                WmItemSplitLine findItem = wmAssembleRecptLineList.get(0);
                WmAssembleRecptLine findRecptLineItem = wmAssembleRecptLineService.getById(findItem.getFromAssembleRecptLineId());
                WmItemRecptLine itemRecptLine1 = wmItemRecptLineService.selectWmItemRecptLineByLineId(findRecptLineItem.getFromItemRecptLineId());

                //统计出库数量
                float aaa = 0;
                if (itemRecptLine1.getQuantityOut() != null){
                    aaa = itemRecptLine1.getQuantityOut().floatValue();
                }
                if (itemSplit.getQuantity() != null){
                    aaa += itemSplit.getQuantity().floatValue();
                }
                itemRecptLine1.setQuantityOut(BigDecimal.valueOf(aaa));

                //修改总库存量
                wmItemRecptLineService.updateById(itemRecptLine1);

                for (int i = 0; i < wmAssembleRecptLineList.size(); i++) {
                    WmItemSplitLine item = wmAssembleRecptLineList.get(i);

                    WmItemRecptLine itemRecptLine = wmItemRecptLineService.getById(item.getFromItemRecptLineId());
                    //统计组装入库数量
                    double aa = itemRecptLine.getQuantityOut().doubleValue() + item.getQuantityRecived().doubleValue();
                    itemRecptLine.setQuantityOut(BigDecimal.valueOf(aa));
                    wmItemRecptLineService.updateById(itemRecptLine);

                    WmAssembleRecptLine assembleRecptLine = wmAssembleRecptLineService.getById(item.getFromAssembleRecptLineId());

                    //来源的
                    WmItemRecptLine itemRecptLine2 = wmItemRecptLineService.getById(assembleRecptLine.getFromItemRecptLineId());

                    WmItemRecptLine wmItemRecptLine = new WmItemRecptLine();
                    wmItemRecptLine.setQuantityRecived(item.getQuantityRecived());
                    wmItemRecptLine.setQuantityOut(BigDecimal.valueOf(0));

                    wmItemRecptLine.setIsInStock("1");
                    wmItemRecptLine.setStatus("1");
                    wmItemRecptLine.setItemId(itemRecptLine2.getItemId());
                    wmItemRecptLine.setItemCode(itemRecptLine2.getItemCode());
                    wmItemRecptLine.setItemName(itemRecptLine2.getItemName());
                    wmItemRecptLine.setSpecification(itemRecptLine2.getSpecification());
                    wmItemRecptLine.setUnitOfMeasure(itemRecptLine2.getUnitOfMeasure());
                    wmItemRecptLine.setInType("4");
                    wmItemRecptLine.setCreateBy(SecurityUtils.getUsername());
                    wmItemRecptLine.setCreateTime(new Date());

                    wmItemRecptLine.setWarehouseId(item.getWarehouseId());
                    if (warehouse != null){
                        wmItemRecptLine.setWarehouseCode(warehouse.getWarehouseCode());
                        wmItemRecptLine.setWarehouseName(warehouse.getWarehouseName());
                    }

                    wmItemRecptLine.setMeterialCode(itemRecptLine2.getMeterialCode());
                    wmItemRecptLine.setBatchCode(itemRecptLine2.getBatchCode());
                    wmItemRecptLine.setExpireDate(itemRecptLine2.getExpireDate());

                    wmItemRecptLineService.save(wmItemRecptLine);

                }

            }
            return apiLog.ok("添加成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }



    /**
     * 删除物料拆分记录
     */
    @PreAuthorize("@ss.hasPermi('wm:wmItemSplitLine:remove')")
    @Log(title = "物料拆分记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{recordIds}")
    public Result<String> remove(@PathVariable Long[] recordIds,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("删除物料拆分记录",req,null);
        try {
            wmItemSplitLineService.delete(recordIds);
            return apiLog.ok("删除成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }

    }
}
